package com.xm.permission;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import java.util.List;
import java.util.Properties;

import static com.xm.permission.AutoStartAccessibilityService.startFindStartupManager;

// AutoStartHelper.java
public class AutoStartHelper {
    private static final String TAG = "AutoStartHelper";
    
    private static AutoStartHelper mInstance;

    private AutoStartHelper() {}

    public static AutoStartHelper getInstance() {
        if (mInstance == null) {
            synchronized (AutoStartHelper.class) {
                if (mInstance == null) {
                    mInstance = new AutoStartHelper();
                }
            }
        }
        return mInstance;
    }

    /**
     * 获取自启动权限
     */
    public void getAutoStartPermission(Activity activity) {
        String manufacturer = getManufacturer().toLowerCase();
        Log.i(TAG, "设备厂商: " + manufacturer);

        // 设置包名到辅助服务
        AutoStartAccessibilityService.setTargetPackage(activity.getPackageName());

        if (isHuaweiDevice()) {
            openHarmonyAutoStartSetting(activity);
        } else if (isXiaomiDevice()) {
            openXiaomiAutoStartSetting(activity);
        } else {
            openDefaultAutoStartSetting(activity);
        }
    }

    /**
     * 获取设备厂商
     */
    public static String getManufacturer() {
        return Build.MANUFACTURER;
    }
    
    /**
     * 判断是否为华为/荣耀设备
     */
    public static boolean isHuaweiDevice() {
        String manufacturer = getManufacturer().toLowerCase();
        return manufacturer.contains("huawei") || manufacturer.contains("honor");
    }
    
    /**
     * 判断是否为小米/红米设备
     */
    public static boolean isXiaomiDevice() {
        String manufacturer = getManufacturer().toLowerCase();
        return manufacturer.contains("xiaomi") || manufacturer.contains("redmi");
    }
    
    /**
     * 判断是否为OPPO设备
     */
    public static boolean isOppoDevice() {
        return getManufacturer().contains("oppo");
    }
    
    /**
     * 判断是否为vivo设备
     */
    public static boolean isVivoDevice() {
        return getManufacturer().contains("vivo");
    }
    
    /**
     * 判断是否为三星设备
     */
    public static boolean isSamsungDevice() {
        return getManufacturer().contains("samsung");
    }
    
    /**
     * 判断是否为魅族设备
     */
    public static boolean isMeizuDevice() {
        return getManufacturer().contains("meizu");
    }
    
    /**
     * 判断是否为一加设备
     */
    public static boolean isOnePlusDevice() {
        return getManufacturer().contains("oneplus");
    }
    
    /**
     * 检测是否为鸿蒙系统
     */
    public static boolean isHarmonyOS() {
        try {
            Class<?> buildExClass = Class.forName("com.huawei.system.BuildEx");
            Object osBrand = buildExClass.getMethod("getOsBrand").invoke(buildExClass);
            return "harmony".equals(osBrand);
        } catch (Exception e) {
            // 另一种检测方法
            try {
                Properties properties = new Properties();
                properties.load(Runtime.getRuntime().exec("getprop ro.build.version.emui").getInputStream());
                return properties.getProperty("ro.build.version.emui", "").contains("harmony");
            } catch (Exception ex) {
                return false;
            }
        }
    }
    
    /**
     * 跳转到对应厂商的自启动设置页面
     * @param context 上下文
     * @return 是否成功跳转
     */
    public static boolean openAutoStartSetting(Context context) {
        try {
            Intent intent = new Intent();
            
            if (isXiaomiDevice()) {
                // 小米/红米
                intent.setComponent(new ComponentName("com.miui.securitycenter",
                        "com.miui.permcenter.autostart.AutoStartManagementActivity"));
                Log.i(TAG, "正在跳转到小米设备自启动设置页面");
            } else if (isOppoDevice()) {
                // OPPO
                intent.setComponent(new ComponentName("com.coloros.safecenter",
                        "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
                Log.i(TAG, "正在跳转到OPPO设备自启动设置页面");
            } else if (isVivoDevice()) {
                // vivo
                intent.setComponent(new ComponentName("com.vivo.permissionmanager",
                        "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
                Log.i(TAG, "正在跳转到vivo设备自启动设置页面");
            } else if (isHuaweiDevice()) {
                // 华为/荣耀
//                if (isHarmonyOS()) {
                    return openHarmonyAutoStartSetting(context); // 鸿蒙系统使用专用方法
//                } else {
//                    intent.setComponent(new ComponentName("com.huawei.systemmanager",
//                            "com.huawei.systemmanager.optimize.bootstart.BootStartActivity"));
//                    Log.i(TAG, "正在跳转到华为EMUI设备自启动设置页面");
//                }
            } else if (isSamsungDevice()) {
                // 三星
                intent.setComponent(new ComponentName("com.samsung.android.lool",
                        "com.samsung.android.sm.ui.battery.BatteryActivity"));
                Log.i(TAG, "正在跳转到三星设备自启动设置页面");
            } else if (isMeizuDevice()) {
                // 魅族
                intent.setComponent(new ComponentName("com.meizu.safe",
                        "com.meizu.safe.security.SHOW_APPSEC"));
                Log.i(TAG, "正在跳转到魅族设备自启动设置页面");
            } else if (isOnePlusDevice()) {
                // 一加
                intent.setComponent(new ComponentName("com.oneplus.security",
                        "com.oneplus.security.chainlaunch.view.ChainLaunchAppListActivity"));
                Log.i(TAG, "正在跳转到一加设备自启动设置页面");
            } else {
                // 其他厂商处理
                Intent detailIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                detailIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
                detailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(detailIntent);
                Log.i(TAG, "正在跳转到应用详情页");
                return true;
            }
            
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            
            if (isIntentAvailable(context, intent)) {
                context.startActivity(intent);
                return true;
            } else {
                // 如果找不到特定页面，尝试跳转到应用详情页
                Intent fallbackIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                fallbackIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
                fallbackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(fallbackIntent);
                Log.i(TAG, "跳转到特定页面失败，使用应用详情页代替");
                return true;
            }
        } catch (Exception e) {
            Log.e(TAG, "跳转自启动设置页面异常", e);
            return false;
        }
    }
    
    /**
     * 鸿蒙系统打开自启动设置
     */
    public static boolean openHarmonyAutoStartSetting(Context context) {
        try {
            // 鸿蒙系统 - 先尝试通用设置入口
            Intent settingsIntent = new Intent();
            settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            
            ComponentName comp = new ComponentName(
                    "com.android.settings",
                    "com.android.settings.Settings$AppAndNotificationDashboardActivity"
            );
            settingsIntent.setComponent(comp);
            
            // 检查是否可用
            PackageManager pm = context.getPackageManager();
            List<ResolveInfo> resolveInfos = pm.queryIntentActivities(settingsIntent,
                    PackageManager.MATCH_DEFAULT_ONLY | PackageManager.MATCH_SYSTEM_ONLY);
            
            if (!resolveInfos.isEmpty()) {
                startFindStartupManager();
                context.startActivity(settingsIntent);
                Log.i(TAG, "成功跳转到鸿蒙系统通用设置入口");
                return true;
            }
            
            // 如果通用入口不可用，使用鸿蒙专用路径
            Intent harmonyIntent = new Intent();
            harmonyIntent.setComponent(new ComponentName(
                    "com.huawei.systemmanager",
                    "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity"));
            harmonyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            
            if (isIntentAvailable(context, harmonyIntent)) {
                context.startActivity(harmonyIntent);
                Log.i(TAG, "成功跳转到鸿蒙系统专用设置入口");
                return true;
            }
            
            // 如果都失败，使用备用方案
            return openAlternativeHuaweiSettings(context);
            
        } catch (Exception e) {
            Log.e(TAG, "跳转鸿蒙自启动设置异常", e);
            return openAlternativeHuaweiSettings(context);
        }
    }
    
    /**
     * 华为备用设置页面
     */
    public static boolean openAlternativeHuaweiSettings(Context context) {
        try {
            // 尝试华为旧版路径
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(
                    "com.huawei.systemmanager",
                    "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity"
            ));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            
            if (isIntentAvailable(context, intent)) {
                context.startActivity(intent);
                Log.i(TAG, "成功跳转到华为备用设置入口");
                return true;
            }
            
            // 最终方案：打开通用电池优化设置
            Intent batteryIntent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
            batteryIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (isIntentAvailable(context, batteryIntent)) {
                context.startActivity(batteryIntent);
                Log.i(TAG, "成功跳转到电池优化设置");
                return true;
            }
            
            // 如果上述都失败，跳转到应用详情页
            Intent detailIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            detailIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            detailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(detailIntent);
            Log.i(TAG, "所有华为设置页跳转失败，使用应用详情页");
            return true;
            
        } catch (Exception e) {
            Log.e(TAG, "打开华为备用设置页异常", e);
            return false;
        }
    }
    
    /**
     * 检查Intent是否可用
     */
    private static boolean isIntentAvailable(Context context, Intent intent) {
        PackageManager packageManager = context.getPackageManager();
        return intent.resolveActivity(packageManager) != null;
    }

    /**
     * 打开小米自启动设置
     */
    public boolean openXiaomiAutoStartSetting(Context context) {
        try {
            // 小米主要自启动设置路径
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            
            // 尝试主要路径 - 新版MIUI
            intent.setComponent(new ComponentName("com.miui.securitycenter", 
                    "com.miui.permcenter.autostart.AutoStartManagementActivity"));
            
            if (isIntentAvailable(context, intent)) {
                AutoStartAccessibilityService.resetAndStartHandling();
                context.startActivity(intent);
                Log.i(TAG, "成功跳转到小米主路径自启动设置");
                return true;
            }
            
            // 尝试备用路径1 - 旧版MIUI
            intent.setComponent(new ComponentName("com.miui.securitycenter", 
                    "com.miui.powercenter.autostart.AutoStartManagementActivity"));
            
            if (isIntentAvailable(context, intent)) {
                AutoStartAccessibilityService.resetAndStartHandling();
                context.startActivity(intent);
                Log.i(TAG, "成功跳转到小米备用路径1自启动设置");
                return true;
            }
            
            // 尝试备用路径2
            intent.setComponent(new ComponentName("com.miui.securitycenter", 
                    "com.miui.optimizer.autostart.AutoStartManagementActivity"));
            
            if (isIntentAvailable(context, intent)) {
                AutoStartAccessibilityService.resetAndStartHandling();
                context.startActivity(intent);
                Log.i(TAG, "成功跳转到小米备用路径2自启动设置");
                return true;
            }
            
            // 尝试最新MIUI 12路径
            intent.setComponent(new ComponentName("com.miui.securitycenter", 
                    "com.miui.securityscan.ui.settings.AutoStartManagementActivity"));
            
            if (isIntentAvailable(context, intent)) {
                AutoStartAccessibilityService.resetAndStartHandling();
                context.startActivity(intent);
                Log.i(TAG, "成功跳转到小米MIUI 12自启动设置");
                return true;
            }
            
            // 尝试安全中心应用管理
            intent.setComponent(new ComponentName("com.miui.securitycenter", 
                    "com.miui.securitycenter.appmanager.AppManagerMainActivity"));
            
            if (isIntentAvailable(context, intent)) {
                AutoStartAccessibilityService.resetAndStartHandling();
                context.startActivity(intent);
                Log.i(TAG, "成功跳转到小米应用管理");
                return true;
            }
            
            // 如果以上都失败，尝试电池优化设置
            Intent batteryIntent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
            batteryIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            
            if (isIntentAvailable(context, batteryIntent)) {
                context.startActivity(batteryIntent);
                Log.i(TAG, "成功跳转到电池优化设置");
                return true;
            }
            
            // 最后尝试应用详情页
            Intent detailIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            detailIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            detailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(detailIntent);
            Log.i(TAG, "所有小米设置路径都失败，使用应用详情页代替");
            return true;
            
        } catch (Exception e) {
            Log.e(TAG, "打开小米自启动设置异常", e);
            
            try {
                // 异常处理：尝试打开应用详情页
                Intent detailIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                detailIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
                detailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(detailIntent);
                Log.i(TAG, "异常后使用应用详情页代替");
                return true;
            } catch (Exception ex) {
                Log.e(TAG, "打开应用详情页也异常", ex);
                return false;
            }
        }
    }

    /**
     * 打开通用自启动设置
     */
    public boolean openDefaultAutoStartSetting(Context context) {
        try {
            // 尝试通用的电池优化设置
            Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "打开通用自启动设置异常", e);
            
            // 如果失败，尝试打开应用详情页
            try {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                return true;
            } catch (Exception ex) {
                Log.e(TAG, "打开应用详情页异常", ex);
                return false;
            }
        }
    }
}